<template>
	<view>
		<!-- 头部标签 -->
		<view class="head displayFlex" :style="{height:winInfo.height-25+'px',paddingTop:winInfo.top-15+'px'}">
			<image @tap="returnTap" style="width: 34rpx" src="/static/return.png" mode="widthFix">
			</image>
			<text>详情页</text>
		</view>
		<view class="" :style="{height:winInfo.height-25+'px',paddingTop:winInfo.top+50+'px'}">
			<view class="activityBox">
				<view class="activityBox-Box" @tap="activityTap()">
					<view class="displayFlexSpaceBetween">
						<view class="activityBox-Box-left">
							{{DataInfo.Biaoti}}
						</view>
						<view class="activityBox-Box-right displayFlex">
							<text style="color: #FB353B;" v-if="DataInfo.HuodongZT === '待同意'">待同意</text>
							<text style="color: #FB353B;" v-if="DataInfo.HuodongZT === '待前往'">待前往</text>
							<text style="color: #437DFA;" v-if="DataInfo.HuodongZT === '进行中'">进行中</text>
							<text style="color: #999999;" v-if="DataInfo.HuodongZT === '已完成'">已完成</text>
							<text style="color: #999999;" v-if="DataInfo.HuodongZT === '已结束'">已结束</text>
						</view>
					</view>
					<view class="activityBox-Box-header displayFlex">
						<image :src="DataInfo.Avatar || '/static/images/my/noAvatar.svg'" mode="aspectFill"
							class="avatar-img">
						</image>
						<view style="margin: 0 20rpx;">{{ DataInfo.Name || '暂无昵称' }}</view>
					</view>
					<view class="activityBox-Box-apply displayFlex">
						<text class="">
							{{ computeHDType(DataInfo) }}
						</text>
						<view>{{ computeHDTime(DataInfo.HuodongSJ) }}</view>
						<text>|</text>
						<view>{{ DataInfo.XiangxiDZ }}</view>
					</view>
					<scroll-view :scroll-x="true" :scroll-y="false" class="scrollAll ">
						<div class="displayFlex" v-if="isTupianMSValid">
							<div class="scrollAll-category" v-for="(item,index) in tupianMSList" :key="index">
								<image :src="Microi.FileServer + item.Path" mode=""></image>
							</div>
						</div>
					</scroll-view>

				</view>

				<view class="timeBox">

					<view class="displayFlexSpaceBetween timeBox-one">
						<text>前往/时间</text>
						<!-- <text>4小时</text> -->
					</view>
					<view class="timeBox-location displayFlexSpaceBetween">
						<view class="" style="width: 440rpx;">
							{{fullAddress}}
						</view>
						<view class="displayFlex" @tap="chooseLocation()">
							<image src="/static/images/my/箭头@2x.png" mode=""></image>
							<text>我的位置</text>
							<image src="/static/images/my/icon-地位@2x.png" mode=""></image>
						</view>
					</view>
					<view class="timeBox-two displayFlexSpaceBetween">
						<view class="">
							<view class="timeBox-two-time">
								预约时间
							</view>
							<view class="timeBox-two-timeDay">
								<!-- <text>05月20日</text>
								<text style="margin: 0 20rpx;">周四</text>
								<text>13：00</text> -->
								{{ computeHDHour(DataInfo.HuodongSJ) }}
							</view>
						</view>
						<view class="">
							<view class="timeBox-two-time">
								离开时间
							</view>
							<view class="timeBox-two-timeDay">
								<!-- <text>05月20日</text>
								<text style="margin: 0 20rpx;">周四</text>
								<text>13：00</text> -->
								{{ computeHDHour(DataInfo.BaomingJZSJ) }}
							</view>
						</view>
					</view>

				</view>
				<view class="phoneBox" v-if="CurrentUser && CurrentUser.Phone">
					<text>手机号码</text>
					<text style="color: #666666;">{{ formatPhone(CurrentUser.Phone) }}</text>
				</view>
				<view class="startOffBox">
					<text style="color: #333333;">预计出发时间 </text>
					<!-- <text>05月02日</text>
					<text>周五</text>
					<text>11:30</text> -->
					{{ computeHDTime(DataInfo.HuodongSJ) }}
				</view>

				<view class="serviceBox" v-if="DataInfo.HuodongZT == '已完成'">
					有疑问？前往咨询<text>客服</text>
				</view>
				<view class="stopApplyBox">

					<view class="stopApplyBox-stop" @tap="stopApplyTap()" v-if="DataInfo.HuodongZT == '已结束'">重新申请
					</view>

					<view class="displayFlexSpaceBetween" style="margin: 0 52rpx;" v-if="DataInfo.HuodongZT == '待同意'">
						<view class="stopApplyBox-cancel" @tap="cancelTap()">
							取消申请
						</view>
						<view class="stopApplyBox-alter" @tap="alterTap()">
							修改信息
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import utils from '@/common/utils.js'
	export default {
		data() {
			return {
				// Islogin: this.Microi.IsLogin(),
				// CurrentUser: this.Microi.Get(),
				CurrentUser: {},
				winInfo: {
					height: 64, //header高度
					top: 26, //标题图标距离顶部距离
					scrollH: 0 //滚动总高度
				},
				DataInfo: "",
				isTupianMSValid: false,
				tupianMSList: [],
				currIndex: 0,
				fullAddress: '',
				Phone: '',
				formattedDate1: '', //预约时间（只保留月和日）
				formattedTime1: '', //预约时间（只保留时和分）
				formattedDate2: '', //离开时间（只保留月和日）
				formattedTime2: '', //离开时间（只保留时和分）
				formattedWeekDay1: '', //预约时间（周几）
				formattedWeekDay2: '', //离开时间（周几）

			}
		},
		mounted() {
			let obj = {}
			// #ifdef MP-WEIXIN
			obj = wx.getMenuButtonBoundingClientRect()
			// #endif
			// #ifdef MP-BAIDU
			obj = swan.getMenuButtonBoundingClientRect()
			// #endif
			// #ifdef MP-ALIPAY
			my.hideAddToDesktopMenu()
			// #endif
			// #ifdef MP-WEIXIN
			setTimeout(() => {
				uni.getSystemInfo({
					success: res => {
						this.winInfo = res
						this.winInfo.width = obj.left || res.windowWidth
						this.winInfo.height = obj.top ? obj.top + obj.height + 8 : res
							.statusBarHeight + 44
						this.winInfo.top = obj.top ? obj.top + (obj.height - 32) / 2 : res
							.statusBarHeight + 6

						this.winInfo.scrollH = res.windowWidth
						this.winInfo.bottom = res.windowHeight
						console.log('信息：', res)
						console.log('底部信息：', this.winInfo.bottom)
					}
				})
			}, 0)
			this.loading = false
			// #endif
		},
		onLoad(options) {
			this.options = options
			console.log("获取ID：", options.Id);
			this.getActivityData()
			const currentUserStr = uni.getStorageSync('CurrentUser');
			if (currentUserStr) {
				const currentUser = JSON.parse(currentUserStr);
				this.CurrentUser = currentUser;
				this.Phone = currentUser.Phone;
			}
		},
		methods: {
			//获取活动列表的详情
			async getActivityData() {
				let res = await this.Microi.FormEngine.GetFormData({
					FormEngineKey: 'diy_huodong',
					Id: this.options.Id
				})
				if (res.Code == 1) {
					this.DataInfo = res.Data || {};
					this.parseTupianMS(this.DataInfo.TupianMS);
					let suoZaiCS = [];
					if (this.DataInfo.SuozaiCS) {
						try {
							// 先替换转义符，再解析
							const formattedStr = this.DataInfo.SuozaiCS.replace(/\\"/g, '"');
							suoZaiCS = JSON.parse(formattedStr);
						} catch (e) {
							console.error('解析SuozaiCS失败:', e);
							suoZaiCS = []; // 解析失败时设为默认空数组
						}
					}

					let xiangxiDZ = this.DataInfo.XiangxiDZ;
					this.fullAddress = suoZaiCS.join("") + xiangxiDZ;
					console.log(this.fullAddress);
					// 其他逻辑...
					return
				} else {
					// 错误处理：设置默认空对象，避免后续报错
					this.DataInfo = {};
					this.Microi.Tips('获取活动信息失败', false);
				}
			},
			async chooseLocation() {
				var self = this;
				await uni.chooseLocation({
					type: 'wgs84',
					success: function(res) {
						console.log(res, 'res');
						self.niDingli(res.latitude, res.longitude);
						const Dingwei = {
							Name: res.name,
							Detail: res.address
						};
						self.DataInfo.HuodongDD = Dingwei;
						self.DataInfo.HuodongDD_Lat = res.latitude;
						self.DataInfo.HuodongDD_Lng = res.longitude;
						console.log(self.DataInfo);
					}
				});
			},
			niDingli(latitude, longitude) {
				console.log(latitude, longitude);
				var self = this;
				var latitude = latitude;
				var longitude = longitude;
				uni.request({
					method: 'GET',
					//注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
					url: `https://restapi.amap.com/v3/geocode/regeo?output=Json&location=${longitude.toFixed(6)},${latitude.toFixed(
						6
					)}&key=6255bb46ab873003124b1e9ce297e2d6&radius=800&extensions=all`,
					success(res) {
						// console.log("获取位置成功", res.data);
						const data = {
							longitude: longitude,
							latitude: latitude,
							address: res.data.regeocode.formatted_address,
							city: res.data.regeocode.addressComponent.city,
							province: res.data.regeocode.addressComponent.province,
							country: res.data.regeocode.addressComponent.country,
							district: res.data.regeocode.addressComponent.district
						};
						console.log(data, 'data');
						if (!data.city || !data.city.length) data.city = '市辖区';
						self.text = data.province + ' ' + data.city + ' ' + data.district;
						self.DataInfo.SuozaiCS = data.province + ' ' + data.city + ' ' + data.district;
						self.DataInfo.HuodongDD.Detail = data.address;
					},
					fail(err) {
						const str = JSON.stringify(err);
						wx.showToast({
							title: 'request_Fail' + err,
							icon: 'none',
							duration: 5000
						});
					}
				});
			},
			formatPhone(Phone) {
				console.log('传入的 Phone：', Phone); // 看是否为预期值
				if (!Phone) return '暂无手机号'
				// 手机号：保留前3后4，中间4位星号
				return utils.hideMiddleStr(Phone, 3, 4)
			},
			parseTupianMS(TupianMS) {
				try {
					// 1. 校验是否为空
					if (!TupianMS) {
						this.isTupianMSValid = false;
						return;
					}
					// 2. 尝试解析 JSON
					const list = JSON.parse(TupianMS);
					this.tupianMSList = list;
					this.isTupianMSValid = true;
				} catch (error) {
					console.error('解析 TupianMS 失败', error);
					this.isTupianMSValid = false;
				}
			},
			/**
			 * 选择标签
			 */
			selectIndex(index) {

				this.currIndex = index;

			},
			activityTap() {
				uni.navigateTo({
					url: '/pages/my/MyAppointment/detailPage'
				});
			},
			stopApplyTap() {
				console.log("停止申请");
			},
			cancelTap() {
				console.log("取消申请");
			},
			alterTap() {
				console.log("修改信息");
			},
			returnTap() {
				uni.navigateBack({
					delta: 1
				});
			},
			computeHDType(item) {
				var HuodongSJ = new Date(item.BaomingJZSJ).getTime();
				var TimeNow = new Date().getTime();
				var baomingCount = item.baomingCount;
				var CanyuRS = item.CanyuRS;
				if (HuodongSJ > TimeNow && baomingCount < CanyuRS) {
					return '报名中';
				} else if (HuodongSJ > TimeNow && baomingCount >= CanyuRS) {
					return '已满员';
				} else if (HuodongSJ <= TimeNow) {
					return '已结束';
				}
			},
			computeHDTime(DataInfo) {
				if (!DataInfo || typeof DataInfo !== 'string') {
					return '时间未知'; // 兜底文案，可自定义
				}

				var time = new Date(DataInfo);
				var year = time.getFullYear();
				var month = time.getMonth() + 1;
				if (month < 10) month = `0${month}`;
				var day = time.getDate();
				if (day < 10) day = `0${day}`;
				var xingqi = time.getDay();
				var XingqiArray = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				xingqi = XingqiArray[xingqi];

				return `${year == new Date().getFullYear() ? '' : year} ${month}月${day}日 ${xingqi} ${DataInfo.split(' ')[1]}`;
			},
			computeNum(num) {
				num = num * 1;
				if (num > 10000) {
					return num / 10000 + 'w+';
				} else if (num > 1000) {
					return num / 1000 + 'k+';
				} else {
					return num;
				}
			},
			// 处理时间显示（不包含秒数）
			computeHDHour(DataInfo) {
				var time = new Date(DataInfo);
				if (isNaN(time.getTime())) {
					return '无效日期';
				}
				const year = time.getFullYear();
				const currentYear = new Date().getFullYear();
				const timeParts = DataInfo.split(' ');
				let timePart = timeParts.length > 1 ? timeParts[1] : '';
			
				// 移除秒数
				if (timePart) {
					// 处理单一时间
					if (!timePart.includes('~')) {
						const parts = timePart.split(':');
						if (parts.length >= 2) {
							timePart = parts[0] + ':' + parts[1];
						}
					} else {
						// 处理时间范围
						const [start, end] = timePart.split('~');
						const startParts = start.split(':');
						const endParts = end.split(':');
						if (startParts.length >= 2 && endParts.length >= 2) {
							timePart = `${startParts[0]}:${startParts[1]}~${endParts[0]}:${endParts[1]}`;
						}
					}
				}
			
				return `${year === currentYear ? '' : year}  ${month}月${day}日 ${xingqi}${timePart}`;
			},

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F7F7;
	}

	.label {
		position: sticky;
		top: 0rpx;
		display: flex;
		//不换行
		white-space: nowrap;

		padding: 22rpx 0 0;
		align-items: center;

		font-family: PingFangSC-Regular;
		font-weight: 400;
		font-size: 28rpx;
		color: #828282;

		.label-item {
			// flex: 1;
			width: 150rpx;
			//行内块 不换行
			display: inline-block;

			view {
				text-align: center;
			}
		}

		.selected-icon {
			width: 130rpx;
			height: 6rpx;
			background: #FB353B;
			border-radius: 8rpx;

			margin: 4rpx auto 0;
		}
	}

	.query-container {

		display: flex;
		justify-content: center;
		align-items: center;
		margin: auto;
		width: calc(100% - 24rpx);
		height: 80rpx;
		border: 2rpx solid rgba(239, 239, 239, 1);
		border-radius: 40rpx;
		position: relative;

		.query-image-text {
			position: absolute;
			display: flex;
			justify-content: center;
			align-items: center;
			gap: 4rpx;

			image {
				width: 32rpx;
				height: 32rpx;
			}

			.query-text {
				font-family: PingFangSC-Regular;
				font-weight: 400;
				font-size: 28rpx;
				color: #C5C5C5;
			}
		}

		input {
			flex: 1;
			font-family: PingFangSC-Regular;
			font-weight: 400;
			font-size: 14px;
			color: #686868;

			padding: 0 27rpx;
		}

	}

	.activityBox {
		margin: 20rpx;

		&-Box {
			margin-top: 16rpx;
			padding: 25rpx;
			background: #FFFFFF;
			border-radius: 16rpx;

			&-left {
				font-weight: 800;
				font-size: 36rpx;
				color: #333333;
			}

			&-right {
				image {
					width: 36rpx;
					height: 36rpx;
				}

				font-weight: 500;
				font-size: 30rpx;
				color: #444444;
			}

			&-header {
				margin: 20rpx 0;

				image {
					width: 44rpx;
					height: 44rpx;
					border-radius: 50%;
				}

				text:nth-of-type(1) {
					font-weight: 800;
					font-size: 26rpx;
					margin: 0 15rpx;
					background: linear-gradient(to right, red, blue);
					-webkit-background-clip: text;
					background-clip: text;
					color: transparent;
				}

				text:nth-of-type(2) {
					font-weight: 800;
					font-size: 26rpx;
					color: #FF7F83;
				}
			}

			&-apply {
				font-weight: 500;
				font-size: 24rpx;
				color: #212121;

				text:nth-of-type(1) {
					font-weight: 500;
					font-size: 24rpx;
					color: #FB353B;
					padding: 4rpx 8rpx;
					background: #FFE9E9;
					border-radius: 6rpx;
				}

				text {
					margin: 0 15rpx;
				}
			}
		}
	}

	.scrollAll {

		&-category {
			text-align: center;
			margin: 20rpx 5rpx 0;

			// padding: 10rpx 30rpx;
			image {
				border-radius: 5rpx;
				width: 214rpx;
				height: 212rpx;
			}
		}
	}

	.stopApplyBox {
		background: #FFF;
		width: 100%;
		padding: 40rpx 0;
		position: fixed;
		left: 0;
		bottom: 0;
		text-align: center;
		background-color: #FFF;
		font-weight: 500;
		font-size: 36rpx;

		// height: 100rpx;
		&-stop {


			color: #FFFFFF;
			background: #FB353B;
			border-radius: 16rpx;
			padding: 20rpx 0rpx;
			margin: 0rpx 30rpx;
		}

		&-cancel {
			padding: 20rpx 74rpx;
			text-align: center;
			border-radius: 16rpx;
			background: #EEEEEE;
			color: #666666;
		}

		&-alter {
			padding: 20rpx 74rpx;
			text-align: center;
			color: #FFFFFF;
			background: #FB353B;
			border-radius: 16rpx;
		}
	}

	.phoneBox {
		background: #FFFFFF;
		border-radius: 16rpx;
		width: 100%;
		padding: 25rpx;
		margin-bottom: 16rpx;

		text {
			font-weight: 500;
			font-size: 30rpx;
			color: #333333;
			margin-right: 10rpx;
		}
	}

	.startOffBox {
		background: #FFFFFF;
		border-radius: 16rpx;
		width: 100%;
		padding: 25rpx;

		text {
			font-weight: 500;
			font-size: 30rpx;
			color: #666666;
			margin-right: 10rpx;
		}
	}

	.timeBox {
		margin: 15rpx 0;
		padding: 30rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		border: 1rpx solid #EEEEEE;

		&-one {
			text:nth-of-type(1) {
				font-weight: 500;
				font-size: 34rpx;
				color: #000000;
			}

			text:nth-of-type(2) {
				font-weight: 500;
				font-size: 26rpx;
				color: #666666;
			}
		}

		&-location {
			padding: 25rpx 0;
			border-bottom: 1rpx solid #EEEEEE;

			view:nth-of-type(1) {
				font-weight: 500;
				font-size: 30rpx;
				color: #212121;
			}

			view:nth-of-type(2) {
				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #FB353B;
					margin: 0 20rpx;
				}

				image:nth-of-type(1) {
					width: 23rpx;
					height: 23rpx;
				}

				image:nth-of-type(2) {
					width: 30rpx;
					height: 30rpx;
				}
			}
		}

		&-two {
			&-time {
				margin: 20rpx 0;
				font-weight: 500;
				font-size: 24rpx;
				color: #999999;
			}

			&-timeDay {
				text:nth-of-type(1) {
					font-weight: 800;
					font-size: 30rpx;
					color: #212121;
				}

				text:nth-of-type(2) {
					font-weight: 500;
					font-size: 25rpx;
					color: #212121;

				}

				text:nth-of-type(3) {
					font-weight: 500;
					font-size: 25rpx;
					color: #212121;

				}
			}
		}
	}

	.serviceBox {
		margin-top: 16rpx;
		text-align: center;
		font-weight: 500;
		font-size: 26rpx;
		color: #999999;

		text {
			color: #FF7F83;
		}
	}

	.head {
		position: fixed;
		left: 0;
		width: 100%;
		top: 0;
		z-index: 1;
		// background-color: #1F9A4F;
		background-color: #fff;

		image {
			margin: 0 0rpx 0 30rpx;
		}

		text {
			font-weight: 800;
			font-size: 34rpx;
			color: #333333;
		}
	}
</style>